package cn.coderliu.producer.controller;

import cn.coderliu.producer.util.RabbitUtil;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author liu
 */
@RestController
public class TestController {


    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RabbitUtil rabbitUtil;

    @GetMapping("/send")
    public String sendDirectMessage() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "test message, hello!";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange

        try {
            rabbitTemplate.convertAndSend("abc", "abc", map, new CorrelationData());
        } catch (Exception e) {
            System.out.println(e.toString());
            throw new RuntimeException();
        }
        return "ok";
    }

    @GetMapping("/test")
    public String test(String a) {
        Queue queue = new Queue(a, true);
        DirectExchange directExchange = new DirectExchange(a);
        rabbitUtil.addExchange(directExchange);
        rabbitUtil.addQueue(new Queue(a));
        rabbitUtil.addBinding(queue, directExchange, a);

        return "ok";
    }

}
